const express = require('express');
const router = express.Router();
const pool = require('../pool.js');

function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
 
    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;
 
      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
 
      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
 
    return uuid.join('');
}

router.post('/submitOrder', function(req, res, next){
	// const { company, fontFamily, font, marking, phone, openid } = req.body;
	const { company, marking, phone, fontSizeId } = req.body;
	pool.getConnection(function(error, connection){
		if(error){
			throw error;
		}

		// 生成一个唯一的订单ID，查找数据库，如果新生成的订单ID已经存在，则重新生成
		// 以此循环，直到生成一个不存在的订单ID，才能插入数据库
		const queryIdSql = 'SELECT * FROM userOrder WHERE order_id = ?';
		let order_id = '';
		while(true){
			order_id = uuid(10,10);
			let flag = true;
			connection.query(queryIdSql, [order_id], function(err, results, fields){
				if(err){
					throw err;
				}
				if(results && results.length > 0){
					flag = false;
				}
			});
			if(flag){
				break;
			}
		}
		

		/*let updateSql = 'UPDATE userOrder SET company=?,font_family=?,font=?,marking=?,phone=?';
		updateSql += ',order_id=?,order_status=?,created_time=? WHERE openid=?';
		const params = [company, fontFamily, font, marking, phone, order_id, 1, new Date(), openid];
		console.log(params);*/

        const insertSql = `INSERT INTO userOrder SET ?`;
        const params = {marking, company, phone, order_id, style_id:fontSizeId, order_status:1, created_time: new Date()};
		connection.query(insertSql, params, function(err, results, fields){
			if(err){
                res.send({
                    code: 500,
                    message: '请求异常',
                });
				throw err;
			}
			connection.release();
            process.send({
				action: 'push',
                marking,
                company,
                phone,
                // openid,
                // font,
                orderId: order_id,
                styleId: fontSizeId,
                orderStatus: 1,
            });

            // 将orderId存到用户本地cookie，缓存时间1小时
            // 打开前端页面时，从cookie中读取orderId，如果读取到则不再展示下单订页面
            // 如果读取不到，则展示下订单页面
            // 限制1小时之内不可以重复下订单
            // res.cookie('orderId', order_id, {maxAge: 60*60*1000});

            res.send({
                code: 200,
                message: 'ok',
                data: results,
            });
			/*if(results.affectedRows && results.changedRows){
				process.send({
					marking,
					company,
					phone,
					// openid,
					// font,
					orderId: order_id,
					styleId: fontSizeId,
					orderStatus: 1,
				});
				res.send({
					code: 200,
					message: 'ok',
					data: results,
				});
			} else {
				res.send({
					code: 500,
					message: '请求异常',
				});
			}*/
			
		});
	});
});

module.exports = router;